﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace XGameLibrary
{
    public class MaskData
    {
        private int cellSize;
        public int CellSize
        {
            get { return cellSize; }
        }
        private byte[,] matrix;
        public byte[,] Matrix
        {
            get { return matrix; }
        }

        public MaskData(int mapWidth, int mapHeight, int cellSize, Point[] maskPoints)
        {
            this.cellSize = cellSize;

            int x = (int)Math.Pow(2, Math.Ceiling(Math.Log(mapWidth / cellSize, 2)));
            int y = (int)Math.Pow(2, Math.Ceiling(Math.Log(mapHeight / cellSize, 2)));
            matrix = new byte[x, y];
            for (int i = 0; i < matrix.GetLength(0); i++)
            {
                for (int j = 0; j < matrix.GetLength(1); j++)
                {
                    matrix[i, j] = 1;
                }
            }
            for (int i = 0; i < maskPoints.Length; i++)
            {
                Point p = maskPoints[i];
                matrix[p.X, p.Y] = 0;
            }
        }

        public void Draw(GameTime gameTime, GraphicsDevice graphicsDevice, SpriteBatch spriteBatch, Camera camera)
        {
            Vector2 offset = camera.Position;
            for (int i = 0; i < matrix.GetLength(0); i++)
            {
                for (int j = 0; j < matrix.GetLength(1); j++)
                {
                    if (matrix[i, j] == 0)
                    {
                        int x = i * cellSize;
                        int y = j * cellSize;
                        Rectangle r = new Rectangle(x, y, cellSize, cellSize);
                        int cpx = (int)camera.Position.X;
                        int cpy = (int)camera.Position.Y;
                        if (r.Intersects(new Rectangle(cpx, cpy, (int)(InputHandler.ScreenWidth/camera.Zoom), (int)(InputHandler.ScreenHeight/camera.Zoom))))
                            Utility.DrawRectangle(graphicsDevice, spriteBatch, new Rectangle((int)((x - cpx) * camera.Zoom), (int)((y - cpy) * camera.Zoom), (int)(cellSize * camera.Zoom), (int)(cellSize * camera.Zoom)), false);
                    }
                }
            }
        }

        public bool IsObstacle(float x, float y)
        {
            return matrix[(int)x / cellSize, (int)y / cellSize] == 0;
        }
    }
}
